package online.flowerinsnow.minecraft.bukkit.manhunt.listener;

import org.bukkit.Bukkit;
import org.bukkit.entity.Entity;
import org.bukkit.entity.Player;
import org.bukkit.entity.Projectile;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageByEntityEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import online.flowerinsnow.minecraft.bukkit.manhunt.event.PlayerAttackEvent;
import online.flowerinsnow.minecraft.bukkit.manhunt.event.PlayerDiedEvent;
import online.flowerinsnow.minecraft.bukkit.manhunt.runnable.DamagerRecordRunnable;

public class DamageListener implements Listener {
    @EventHandler(ignoreCancelled = true)
    public void onDamage(EntityDamageEvent e) {
        if (e instanceof EntityDamageByEntityEvent) {
            EntityDamageByEntityEvent var1 = (EntityDamageByEntityEvent) e;
            Entity damager = var1.getDamager();
            if (damager instanceof Projectile) {
                Projectile projectile = (Projectile) damager;
                if (projectile.getShooter() instanceof Entity) {
                    damager = (Entity) projectile.getShooter();
                } else damager = projectile;
            }
            if (damager instanceof Player) {
                Player damagePlayer = (Player) damager;
                PlayerAttackEvent event = new PlayerAttackEvent(damagePlayer, var1);
                Bukkit.getPluginManager().callEvent(event);
                if (event.isCancelled()) return;
            }
            if (e.getEntity() instanceof Player) {
                Player player = (Player) e.getEntity();
                DamagerRecordRunnable.setLastDamager(player, damager);
            }
        }
        if (e.getEntity() instanceof Player) {
            Player player = (Player) e.getEntity();
            double originalHealth = player.getHealth() + player.getAbsorptionAmount();
            if (originalHealth - e.getFinalDamage() <= 0) {
                PlayerDiedEvent event = new PlayerDiedEvent(player, e.getCause(), DamagerRecordRunnable.getLastDamager(player));
                Bukkit.getPluginManager().callEvent(event);
                if (event.cancel) {
                    e.setCancelled(true);
                    return;
                }
                e.setDamage(0);
                DamagerRecordRunnable.resetLastDamager(player);
            }
        }
    }
}
